import React, { useLayoutEffect, useState, useRef } from 'react';

import { Icon } from 'antd';
import { ActivityIndicator, InputItem, Modal, Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import { useMount } from 'react-use';
import { router, withRouter } from 'umi';

import { createDictionary } from '@/dictionary';
import { defaultFormatResult, useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import CustomNavBar from '@/pages/EntryManage/mobile/components/CustomNavBar';
import EntryMetaTag from '@/pages/EntryManage/mobile/components/EntryMetaTag';
import {
    deleteEmployeeWorkDataById,
    fetchEmployeeArchivesData,
    getWorkById,
    saveEmployeeWorkSingle
} from '@/pages/EntryManage/services';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { Button, DateRangePicker, EditListItem, Picker, Radio } from '@/pages/RecruitEmail/mobile/components';

import styles from './index.less';

const [workExperienceList] = createDictionary('WORK_EXPERIENCE_DICT', { textKey: 'label' });
const PhoneType = props => (
    <div onClick={props.onClick} style={{ flex: 1, fontSize: 16, color: '#bcc1cd' }}>
        {props.extra} <Icon style={{ fontSize: 10 }} type="caret-down" />
    </div>
);

/**
 * 入职员工工作经历
 */
const EntryEmployeeWorkMobile = ({ form, location }) => {
    const [pageError, setPageError] = useState();
    const { query } = location;
    const { entryPersonnelCode, id } = query;
    const { getFieldProps, getFieldValue, resetFields } = form;
    const [industryTypeList] = useDictionary('industryType', { textKey: 'label' });
    const { hasFormChange, initialForm } = useFormChange(form);
    const entryEmployeeWorkMobileRef = useRef();

    const handleScrollTop = () => {
        entryEmployeeWorkMobileRef.current.scrollTo(0, 0);
    };
    // 获取数据
    const { data: employeeArchivesData, loading: employeeArchivesLoading, refresh } = useRequest(
        () => fetchEmployeeArchivesData(entryPersonnelCode),
        {
            refreshDeps: [entryPersonnelCode],
            ready: !!entryPersonnelCode,
            ...defaultFormatResult,
            onSuccess: () => {
                initialForm();
            }
        }
    );
    useMount(() => {
        if (!id) {
            initialForm();
        }
    });
    const { data: formData, loading: formDataLoading, error: formDataError } = useRequest(() => getWorkById(id), {
        refreshDeps: [id],
        ready: !!id,
        ...defaultFormatResult
    });
    // 提交
    const { run: submitRun, loading: submitLoading } = useRequest(submitData => saveEmployeeWorkSingle(submitData), {
        manual: true
    });

    // 提交
    const handleSubmit = isContinueAdd => {
        form.validateFields((err, values) => {
            if (!err) {
                // 没有工作经验的时候进入, 会出现工作经验这一栏, 否则取原有的值
                const workExperience = employeeArchivesData?.workList?.length
                    ? employeeArchivesData.workExperience
                    : values.workExperience;
                let submitData = {
                    entryPersonnelCode,
                    workExperience,
                    id
                };
                // 有工作经验才附带表单的值
                if (workExperience === 1) {
                    submitData = {
                        ...submitData,
                        startTime: values.rangeDate?.[0] && values.rangeDate[0],
                        endTime: values.rangeDate?.[1] ? values.rangeDate[1] : null,
                        organize: values.organize,
                        industry: values?.industry?.length && values.industry[0],
                        post: values.post,
                        reason: values.reason,
                        areaCode: values?.areaCode?.length && values.areaCode[0],
                        approveName: values.approveName,
                        approvePhone: values.approvePhone
                    };
                }
                // 提交
                submitRun(submitData).then(res => {
                    if (res.code === 10000) {
                        Toast.info('保存成功', 3, null, false);
                        if (isContinueAdd) {
                            resetFields();
                            refresh();
                            handleScrollTop();
                        } else {
                            history.goBack();
                        }
                    } else {
                        Toast.info(res.msg);
                    }
                });
            } else {
                const errorList = Object.values(err);
                if (errorList && errorList.length > 0) {
                    const { errors } = errorList[0];
                    Toast.info(errors[0]?.message, 3, null, false);
                }
            }
        });
    };

    const getWorkExperience = () =>
        employeeArchivesData?.workList?.length ? employeeArchivesData.workExperience : getFieldValue('workExperience');

    // 删除
    const handleDelete = () => {
        if (!id) {
            return;
        }
        Toast.loading('提交中...', 5000);
        deleteEmployeeWorkDataById({ entryPersonnelCode, id })
            .then(res => {
                const { code, msg } = res;
                if (code === 10000) {
                    Toast.info('删除成功', 3, null, false);
                    history.goBack();
                } else {
                    Toast.info(msg);
                }
            })
            .finally(() => {
                Toast.hide();
            });
    };

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    useLayoutEffect(() => {
        // 参数校验
        if (!entryPersonnelCode) {
            setPageError('参数无效');
        }
    }, [entryPersonnelCode]);

    if (pageError || formDataError) {
        return <div className={styles.pageError}>{pageError?.msg || formDataError?.msg || '加载错误'}</div>;
    }

    return (
        <>
            {(formDataLoading || employeeArchivesLoading || submitLoading) && (
                <ActivityIndicator toast text="正在加载" />
            )}
            {!id || formData ? (
                <div className={styles.entryMobileContainer}>
                    <EntryMetaTag />
                    <CustomNavBar onLeftClick={handleLeftClick}>工作经验</CustomNavBar>
                    <div className="formContainer formContainerFixed" ref={entryEmployeeWorkMobileRef}>
                        {!employeeArchivesLoading && employeeArchivesData?.workList?.length === 0 && (
                            <EditListItem title="工作经验" showArrow={false}>
                                <Radio
                                    className="customRadioBlock"
                                    dataSource={workExperienceList}
                                    {...getFieldProps('workExperience', {
                                        initialValue: employeeArchivesData?.workExperience,
                                        rules: [{ required: true, message: '请选择工作经验' }]
                                    })}
                                />
                            </EditListItem>
                        )}
                        {(employeeArchivesData?.workList?.length > 0 || getFieldValue('workExperience') === 1) && (
                            <>
                                <EditListItem title="起止时间">
                                    <DateRangePicker
                                        {...getFieldProps('rangeDate', {
                                            initialValue:
                                                formData?.startTime || formData?.endTime
                                                    ? [formData?.startTime, formData?.endTime]
                                                    : undefined,
                                            rules: [{ required: true, message: '请选择起止时间' }]
                                        })}
                                        showNow
                                    >
                                        请选择
                                    </DateRangePicker>
                                </EditListItem>
                                <Picker
                                    title="行业"
                                    data={industryTypeList}
                                    className={styles.customPicker}
                                    cols={1}
                                    {...getFieldProps('industry', {
                                        initialValue: formData?.industry ? [formData?.industry] : undefined,
                                        rules: [{ required: true, message: '请选择行业' }]
                                    })}
                                >
                                    <EditListItem title="行业">请选择</EditListItem>
                                </Picker>
                                <EditListItem title="公司" showArrow={false}>
                                    <InputItem
                                        {...getFieldProps('organize', {
                                            initialValue: formData?.organize || '',
                                            rules: [
                                                { required: true, message: '请输入公司' },
                                                { max: 100, message: '公司字数不能超过100个字符' }
                                            ]
                                        })}
                                        clear
                                        placeholder="请输入"
                                        maxLength={100}
                                    />
                                </EditListItem>
                                <EditListItem title="职位职级" showArrow={false}>
                                    <InputItem
                                        {...getFieldProps('post', {
                                            initialValue: formData?.post || '',
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入职位职级'
                                                },
                                                {
                                                    max: 50,
                                                    message: '职位职级不能超过50个字符'
                                                }
                                            ]
                                        })}
                                        clear
                                        placeholder="请输入"
                                        maxLength={100}
                                    />
                                </EditListItem>
                                <EditListItem title="离职原因(选填)" showArrow={false}>
                                    <InputItem
                                        {...getFieldProps('reason', {
                                            initialValue: formData?.reason || '',
                                            rules: [{ max: 100, message: '离职原因字数不能超过100个字符' }]
                                        })}
                                        clear
                                        placeholder="请输入"
                                        maxLength={100}
                                    />
                                </EditListItem>
                                <EditListItem title="证明联系人(选填)" showArrow={false} bordered={false}>
                                    <InputItem
                                        {...getFieldProps('approveName', {
                                            initialValue: formData?.approveName || '',
                                            rules: [{ max: 50, message: '证明联系人字数不能超过50个字符' }]
                                        })}
                                        clear
                                        placeholder="请输入"
                                        maxLength={100}
                                    />
                                </EditListItem>
                                <EditListItem title="手机号(选填)" showArrow={false}>
                                    <div style={{ display: 'flex', alignItems: 'center' }}>
                                        <Picker
                                            title="选择国际电话区号"
                                            className={styles.customPicker}
                                            data={[
                                                { label: '+86', value: '86' },
                                                { label: '+65', value: '65' }
                                            ]}
                                            {...getFieldProps('areaCode', {
                                                initialValue: [formData?.areaCode || '86']
                                            })}
                                        >
                                            <PhoneType />
                                        </Picker>
                                        <div className={styles.mobileAddStyle}>
                                            <InputItem
                                                {...getFieldProps('approvePhone', {
                                                    initialValue: formData?.approvePhone || '',
                                                    rules: [
                                                        {
                                                            validator(rule, value, callback) {
                                                                const regex = /^\d{7,11}$/;
                                                                if (!value) {
                                                                    callback();
                                                                } else if (!regex.test(value)) {
                                                                    callback('手机号只能输入7-11位数字');
                                                                }
                                                                callback();
                                                            }
                                                        }
                                                    ]
                                                })}
                                                clear
                                                placeholder="请输入手机号"
                                            />
                                        </div>
                                    </div>
                                </EditListItem>
                            </>
                        )}
                    </div>
                    <div className="formControls">
                        {query?.id ? (
                            <>
                                <Button style={{ marginRight: 15, flex: 1 }} onClick={handleDelete}>
                                    删除
                                </Button>
                                <Button type="primary" style={{ flex: 1 }} onClick={handleSubmit}>
                                    完成
                                </Button>
                            </>
                        ) : (
                            <>
                                <Button
                                    style={{ marginRight: 15, flex: 1 }}
                                    type={getWorkExperience() === 1 ? 'default' : 'primary'}
                                    onClick={handleSubmit}
                                >
                                    保存
                                </Button>
                                {getWorkExperience() === 1 && (
                                    <Button style={{ flex: 1 }} type="primary" onClick={() => handleSubmit(true)}>
                                        保存并继续添加
                                    </Button>
                                )}
                            </>
                        )}
                    </div>
                </div>
            ) : null}
        </>
    );
};

export default withRouter(createForm()(EntryEmployeeWorkMobile));
